#pragma once
#include <iostream>
#include <string>
#include <unistd.h>
#include <thread>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
using namespace std;

//双方通信使用的文件
const string gpipefile = "./fifo";
const mode_t gmode = 0600;//允许拥有者写，所属组和other什么权限都没有
const int gdefulted = -1;
const int gsize = 1024;
const int gForRead = O_RDONLY;
const int gForWrite = O_WRONLY;

class Fifo
{
private:
    void OPenFifo(int flag)
    {
        //以只读方式打开
        _fd = open(gpipefile.c_str(),flag);
        if(_fd < 0)
        {
            cerr<<"open error"<<endl;
        }
    }
public:
    Fifo():_fd(-1){
        umask(0);//先将缺省权限清零
        int n = mkfifo(gpipefile.c_str(),gmode);
        if(n < 0)//创建管道文件失败
        {
            cerr<<"mkfifo error"<<endl;
            return;
        }
        cout<<"mkfifo success"<<endl;
    }
    bool OpenPipeForRead()
    {
        OPenFifo(gForRead);
        if(_fd < 0)return false;
        return true;
    }
    bool OpenpipeForWrite()
    {
        OPenFifo(gForWrite);
        if(_fd < 0) return false;
        return true;
    }
    //读取消息-
    int Wait()
    {
        int code = 0;
        //读取文件
        ssize_t n = read(_fd,&code,sizeof(code));//预留一个空间，后面是期望读这么多，n是实际读取的字节数
        if(n == sizeof(code)) return 0;
        else if(n == 0) return 1;
        else return 2;
    }
    void Signal()
    {
        int code = 1;
        write(_fd,&code,sizeof(code));
    }
    ~Fifo(){
        //析构的时候顺便把管道文件关闭了
        if(_fd >= 0) close(_fd);
        //删除当前路径下的文件
        int n = unlink(gpipefile.c_str());
        //判断是否删除成功
        if(n < 0)
        {
            cerr<<"unlink error"<<endl;
            return;
        }
        cout<<"unlink success"<<endl;
    }
private:
    int _fd;
};

Fifo gpipe;